package com.klhappy.houyuan.activity;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.klhappy.houyuan.R;
import com.klhappy.houyuan.bean.BaseJsonBean;
import com.klhappy.houyuan.bean.FamilyInt;
import com.klhappy.houyuan.constant.KeyConstant;
import com.klhappy.houyuan.constant.UrlConstant;
import com.klhappy.houyuan.dialog.Photograph;
import com.klhappy.houyuan.interfaces.CallBackInterModle;
import com.klhappy.houyuan.modle.JiaYuanModle;
import com.klhappy.houyuan.utils.Multipart.MultipartRequest;
import com.klhappy.houyuan.utils.headshot.CacheInfo;
import com.klhappy.houyuan.utils.headshot.CropImageActivity;
import com.klhappy.houyuan.utils.headshot.HeadShotUtil;
import com.klhappy.houyuan.utils.headshot.UserInfoCacheUtil;
import com.klhappy.houyuan.utils.okhttp.BaseBeanCallback;
import com.klhappy.houyuan.utils.okhttp.ImgBean;
import com.klhappy.houyuan.utils.okhttp.OkHttpUtils;
import com.klhappy.houyuan.utils.okhttp.callback.BitmapCallback;
import com.klhappy.houyuan.utils.okhttp.callback.StringCallback;
import com.klhappy.houyuan.view.AbsActivity;
import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2015/11/17.
 */
public class AddFamilyActivity extends AbsActivity implements CallBackInterModle {

    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.head_img)
    ImageView head_img;
    @InjectView(R.id.relation)
    EditText relation;
    @InjectView(R.id.sex)
    EditText sex;
    @InjectView(R.id.phone)
    EditText phone;
    @InjectView(R.id.adress)
    EditText adress;
    @InjectView(R.id.door_num)
    EditText door_num;
    @InjectView(R.id.occupation)
    EditText occupation;
    @InjectView(R.id.birthday)
    EditText birthday;
    @InjectView(R.id.love)
    EditText love;
    @InjectView(R.id.weight)
    EditText weight;

    @OnClick(R.id.click_ra)
    public void click_ra() {
        finish();
    }

    @OnClick(R.id.head_lay)
    public void head_lay() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        int num = (int) (Math.random() * 100);
        imgName = date + "header" + num + ".png";
        mConfigManage.set(KeyConstant.FAMILY ,imgName);
        isKey = KeyConstant.FAMILY;
        photograph = new Photograph(this) {
            @Override
            public void doGoToImg() {
                super.doGoToImg();
                this.dimiss();
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, KeyConstant.FLAG_CHOOSE_IMG);
            }

            @Override
            public void doGoToPhone() {
                super.doGoToPhone();
                this.dimiss();
                String status = Environment.getExternalStorageState();
                if (status.equals(Environment.MEDIA_MOUNTED)) {
                    try {
                        localTempImageFileName = mConfigManage.get(KeyConstant.FAMILY ,"");
                        if (!mHeadShotDir.exists()) {
                            mHeadShotDir.mkdirs();
                        }
                        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        File f = new File(mHeadShotDir, localTempImageFileName);
                        Uri u = Uri.fromFile(f);
                        intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                        startActivityForResult(intent, KeyConstant.FLAG_CHOOSE_PHONE);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(AddFamilyActivity.this,
                                "相机打开失败", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(AddFamilyActivity.this, "手机未安装SD卡",
                            Toast.LENGTH_SHORT).show();
                }
            }
        };

        photograph.show();
    }

    @OnClick(R.id.add_tv)
    public void add_tv() {
        if (TextUtils.isEmpty(relation.getText().toString())){
            showToastx("请输入和您的关系");
        }else if (TextUtils.isEmpty(phone.getText().toString())){
            showToastx("请输入电话号码");
        }else if (TextUtils.isEmpty(adress.getText().toString())){
            showToastx("请输入地址");
        }else if (TextUtils.isEmpty(door_num.getText().toString())){
            showToastx("请输入门号");
        }else {
            intFamily();
            showDialog("请稍等...");
        }
    }

    private File file_sdcard;
    private File mHeadShotDir;
    private File imageToUpload;
    private static String localTempImageFileName = "";
    private Photograph photograph;
    private FamilyInt familyInt;
    private JiaYuanModle modle;
    private String imgName;
    private String isKey;//表示存储的key

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_family);
        ButterKnife.inject(this);
        title.setText("添加成员");

        initImageFileCache();
//        initData();

        familyInt = new FamilyInt();
        modle = new JiaYuanModle(this);
        modle.setCallBackInterModle(this);

    }

    private void intFamily() {
        familyInt.setRelation(relation.getText().toString());
        familyInt.setPhone(phone.getText().toString());
        familyInt.setSex(sex.getText().toString());
        familyInt.setAdress(adress.getText().toString());
        familyInt.setDoor_num(door_num.getText().toString());
        familyInt.setOccupation(occupation.getText().toString());
        familyInt.setBirthday(birthday.getText().toString());
        familyInt.setLove(love.getText().toString());
        familyInt.setWeight(weight.getText().toString());

        Map<String, String> params = new HashMap<>();
        params.put("relation", familyInt.getRelation());
        params.put("sex", familyInt.getSex());
        params.put("own_mob_no", familyInt.getPhone());
        params.put("job", familyInt.getOccupation());
        params.put("hobby", familyInt.getLove());
        params.put("weight", familyInt.getWeight());
        params.put("address", familyInt.getAdress());

        Map<String, String> headers = new HashMap<>();
        headers.put("cookie", mConfigManage.get(KeyConstant.session, ""));

        String url = UrlConstant.ADDMEMBER_URL;

        String header = mConfigManage.get(KeyConstant.FAMILY, "");
        imageToUpload = new File(mHeadShotDir, header);

        OkHttpUtils.post()
                .addFile("file", mConfigManage.get(KeyConstant.FAMILY, ""), imageToUpload)
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new BaseBeanCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        Log.e("this", e.toString());
                        closeDialog();
                    }

                    @Override
                    public void onResponse(ImgBean imgBean) {
                        Gson gson = new Gson();
                        Log.e("this", gson.toJson(imgBean));
                        showToastx(imgBean.msg);
                        closeDialog();
                        finish();
                    }
                });
    }

    @Override
    public void CallBackFromModle(String url, BaseJsonBean o) {
        if (url.equals(UrlConstant.ADDMEMBER_URL)) {
            showToastx(o.getMsg());
            closeDialog();
            if (o.getCode() == 200) {
                finish();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == KeyConstant.FLAG_CHOOSE_IMG
                && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (!TextUtils.isEmpty(uri.getAuthority())) {
                    Cursor cursor = getContentResolver().query(uri,
                            new String[]{MediaStore.Images.Media.DATA},
                            null, null, null);
                    if (null == cursor) {
                        showToastx("图片没找到!");
                        return;
                    }
                    cursor.moveToFirst();
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    cursor.close();
                    Intent intent = new Intent(this, CropImageActivity.class);
                    intent.putExtra("path", path);
                    intent.putExtra("key" ,isKey);
                    startActivityForResult(intent, KeyConstant.FLAG_MODIFY_FINISH);
                } else {
                    Intent intent = new Intent(this, CropImageActivity.class);
                    intent.putExtra("path", uri.getPath());
                    intent.putExtra("key" ,isKey);
                    startActivityForResult(intent,
                            KeyConstant.FLAG_MODIFY_FINISH);
                }
            }
        } if (requestCode == KeyConstant.FLAG_CHOOSE_PHONE
                && resultCode == RESULT_OK) {
            File f = new File(mHeadShotDir, localTempImageFileName);
            Intent intent = new Intent(this, CropImageActivity.class);
            intent.putExtra("path", f.getAbsolutePath());
            intent.putExtra("key" ,isKey);
            startActivityForResult(intent, KeyConstant.FLAG_MODIFY_FINISH);
        } if (requestCode == KeyConstant.FLAG_MODIFY_FINISH
                && resultCode == RESULT_OK) {
            if (data != null) {
                String imgName = mConfigManage.get(KeyConstant.FAMILY, "");
                Bitmap headShot = HeadShotUtil.getHeadShot(imgName);
                if (headShot != null) {
                    head_img.setImageBitmap(headShot);
                }
            }
        }
    }

    //创建文件夹
    private void initImageFileCache() {
        file_sdcard = Environment.getExternalStorageDirectory();
        mHeadShotDir = new File(file_sdcard, KeyConstant.APP_DIR
                + File.separator + KeyConstant.IMAGE_DIR + File.separator
                + KeyConstant.HEAD_SHOT);
        if (!mHeadShotDir.exists()) {
            mHeadShotDir.mkdirs();
        }
    }
}
